package com.ning.cloud.user.controller;

import com.ning.cloud.common.exception.ServiceException;
import com.ning.cloud.common.util.Response;
import com.ning.cloud.framework.security.UserContext;
import com.ning.cloud.framework.security.dto.AuthUserDTO;
import com.ning.cloud.user.dto.UserLoginDTO;
import com.ning.cloud.user.dto.UserRegisterDTO;
import com.ning.cloud.user.request.UserLoginRequest;
import com.ning.cloud.user.request.UserRegisterRequest;
import com.ning.cloud.user.service.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * </p>
 *
 * @since 2025-07-03
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Tag(name = "用户管理模块")
public class UserController {

    @Resource
    AdminUserService adminUserService;

    @GetMapping("/info")
    @Operation(summary = "查询用户信息")
    public Response<AuthUserDTO> info(){
        AuthUserDTO authUserDTO = UserContext.getAuthUser();
        return Response.success(authUserDTO);
    }


    @GetMapping("/exception")
    public Response<?> testException(){
        if (true) {
            throw new ServiceException();
        }
        return Response.success();
    }

    /**
     * 测试oom
     * jvm配置：-Xmx200m -Xms200m -Xlog:gc* -XX:+HeapDumpOnOutOfMemoryError
     * @return
     */
    @PostMapping("/test")
    public String test(){

        List<Object> list = new ArrayList<>();
        int count = 0;

        try {
            while (true) {
                // 每次生成一个 1MB 的数组，强引用放进 list，无法被 GC 回收
                byte[] data = new byte[1024 * 1024];
                list.add(data);
                count++;
                if (count % 5 == 0) {
                    System.out.println("Allocated objects: " + count + " MB");
                }
            }
        } catch (OutOfMemoryError e) {
            System.err.println("OOM triggered after allocating: " + count + " MB");
            e.printStackTrace();
        }

        return "test";
    }


    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Response<UserRegisterDTO> register(@RequestBody @Valid UserRegisterRequest userRegisterRequest){
        UserRegisterDTO userRegisterDTO = adminUserService.register(userRegisterRequest);
        return Response.success(userRegisterDTO);
    }


    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Response<UserLoginDTO> login(@RequestBody @Valid UserLoginRequest userLoginRequest){
        UserLoginDTO userLoginDTO = adminUserService.login(userLoginRequest);
        return Response.success(userLoginDTO);
    }



}
